package cn.east196.tfx.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.boot.SpringApplication;
import org.springframework.context.ApplicationContext;

import com.jfinal.kit.PropKit;

import cn.east196.xfx.StagePool;
import cn.east196.xfx.controls.MessageBox;
import cn.edu.scau.biubiusuisui.annotation.FXScan;
import cn.edu.scau.biubiusuisui.config.FXPlusApplication;
import cn.edu.scau.biubiusuisui.factory.BeanBuilder;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.stage.Stage;

@FXScan(base = { "cn.east196.tfx.controller" })
public class App extends Application {

	private static Logger logger = LogManager.getLogger(App.class);

	@Override
	public void start(Stage primaryStage) throws Exception {
//		ApplicationContext context = SpringApplication.run(App.class);
//		FXPlusApplication.start(InitializerPlus.class, new BeanBuilder() {
//			@Override
//			public Object getBean(Class type) {
//				return context.getBean(type); // 接管FXPlus属性的创建
//			}
//		});
		FXPlusApplication.start(App.class);
//		initTemplete();
	}
	
	public static void main(String[] args) {
		PropKit.use("config/config.properties");
		Application.launch(App.class);
	}
	
	private void initTemplete() {
		PropKit.use("config/config.properties");
		String templeteDir = System.getProperty("user.home") + PropKit.get("app.templeteDir");
		String[] templetes = PropKit.get("app.templetes").split(",");
		String tempExt = ".ftl";
		File propDir = new File(templeteDir);
		File tempFile;
		if (!propDir.exists()) {
			if (!propDir.mkdirs()) {
				MessageBox.error("main", "templete file load error.");
			}
		}
		for (String tempName : templetes) {
			tempFile = new File(templeteDir + tempName + tempExt);
			if (!tempFile.exists()) {
				copyTempete("/templete/" + tempName + tempExt, templeteDir + tempName + tempExt);
			}
		}
		logger.debug("templete dir:" + templeteDir);
	}

	private void copyTempete(String resourceDir, String destDir) {
		InputStream in = null;
		FileOutputStream out = null;
		try {
			int byteread;
			in = getClass().getResourceAsStream(resourceDir);
			File destFile = new File(destDir);
			out = new FileOutputStream(destFile);
			byte[] buffer = new byte[1024];
			while ((byteread = in.read(buffer)) != -1) {
				out.write(buffer, 0, byteread);
			}
		} catch (IOException e) {
			logger.error(e);
		} finally {
			try {
				assert in != null;
				in.close();
				assert out != null;
				out.close();
			} catch (IOException e) {
				logger.error(e);
			}
		}
	}

}
